﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using StripeOne.Core.Cache;
using StripeOne.Core.Common;
using System.IO;
using StripeOne.Core.Log;

namespace StripeOne.Core.Config
{
    public class ConfigXml
    {
        #region Attributes
        
        private static FileWatcher Watcher = new FileWatcher();

        #endregion

        #region Public Methods
        
        public static XDocument LoadXml(string fileName, bool isDictionary, int cacheTime = 0, string cacheKey = "")
        {
            var cache = new StripeOneCache();
            if (string.IsNullOrWhiteSpace(cacheKey))
                cacheKey = "ConfigXml_LoadXml_" + fileName;
            return (XDocument)cache.AutoCache<string, bool, string, XDocument>(cacheKey, cacheTime, (res, res1, res2) => LoadXmlNoCache(fileName, isDictionary, cacheKey), fileName, isDictionary, cacheKey).Value;
        }
        
        public static string GetConfigFolderPath()
        {
            return AppDomain.CurrentDomain.BaseDirectory + @"Config\";
        }

        #endregion

        #region Private Methods
        
        private static XDocument LoadXmlNoCache(string fileName, bool isDictionary = false, string cacheKey = "")
        {
            try
            {
                var pathSeparator = Path.DirectorySeparatorChar;

                var path = GetConfigFolderPath();

                Watcher.Path = path;
                Watcher.FileName = fileName;
                Watcher.CacheKey = cacheKey;
                Watcher.Start();

                if (isDictionary)
                    path += "Dictionary" + pathSeparator;
                path += fileName + ".xml";
                StripeOneLog.Verbose("Loading configuration file: [" + path + "]");
                return XDocument.Load(path);
            }
            catch (FileNotFoundException ex)
            {
                StripeOneLog.Warning(string.Format("Configuration file not found: [{0}/{1}]", ex.FileName));
                return null;
            }
            catch (Exception ex)
            {
                StripeOneLog.Exception(ex);
                return null;
            }
        }

        #endregion
    }
}
